import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class JakespecParser {
    public Jakespec parse() throws FileNotFoundException {
        return parse("Jakespec");
    }

    public Jakespec parse(String jakespecPath) throws FileNotFoundException {
        File jakespecFile = new File(jakespecPath);
        if (!jakespecFile.exists() || !jakespecFile.isFile()) {
            throw new FileNotFoundException("路径：" + jakespecFile.getAbsolutePath());
        }

        Map<String, String> globalConfig = new HashMap<>();
        Map<String, Target> targets = new HashMap<>();
        Target currentTarget = null;

        try (Scanner scanner = new Scanner(jakespecFile)) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                
                // 关键修复1：先修剪行首空格，再判断是否为注释（忽略#及后面内容）
                line = line.trim();
                // 完全忽略注释行（#开头）
                if (line.isEmpty() || line.startsWith("#")) {
                    continue;
                }
                // 关键修复2：去除行内注释（#及后面内容）
                int commentIndex = line.indexOf("#");
                if (commentIndex != -1) {
                    line = line.substring(0, commentIndex).trim();
                    // 如果去除注释后为空行，直接跳过
                    if (line.isEmpty()) {
                        continue;
                    }
                }

                if (line.startsWith("-") && line.contains(":")) {
                    parseConfigLine(line, globalConfig, currentTarget);
                    continue;
                }

                if (line.endsWith(":")) {
                    String targetName = line.substring(0, line.length() - 1).trim();
                    currentTarget = new Target(targetName);
                    targets.put(targetName, currentTarget);
                    continue;
                }

                if (currentTarget != null) {
                    currentTarget.addCommand(line);
                }
            }
        }

        return new Jakespec(globalConfig, targets);
    }

    private void parseConfigLine(String line, Map<String, String> globalConfig, Target currentTarget) {
        int colonIndex = line.indexOf(":");
        if (colonIndex <= 1) {
            return;
        }

        String key = line.substring(1, colonIndex).trim();
        String value = line.substring(colonIndex + 1).trim();

        if (currentTarget == null) {
            globalConfig.put(key, value);
        } else {
            parseTargetConfig(key, value, currentTarget);
        }
    }

    private void parseTargetConfig(String key, String value, Target target) {
        switch (key) {
            case "depends":
                String[] deps = value.split("[,\\s]+");
                for (String dep : deps) {
                    if (!dep.isEmpty()) {
                        target.addDependency(dep);
                    }
                }
                break;
            case "javacarg":
                target.addCompilerArg(value);
                break;
            case "fatjar":
                target.addProperty("fatjar", value);
                break;
            case "mainclass":
                target.addProperty("mainclass", value);
                break;
            case "classpath":
                target.setClasspath(value);
                break;
            case "sourcedir":
                target.setSourceDir(value);
                break;
            case "outputdir":
                target.setOutputDir(value);
                break;
            case "directory":
                target.setDirectory(value);
                break;
            default:
                System.out.println("⚠️  警告：未知配置项 - " + key);
                break;
        }
    }
}
